require 'websocket-client-simple'
require 'redis'
redis = Redis.new

url = ARGV[0] || 'ws://localhost:8003'
logfile = ARGV[1]

if logfile
  $stdout.reopen(logfile, 'w')
  $stdout.sync = true
  $stderr.reopen($stdout)
end


ws = WebSocket::Client::Simple.connect(url)

ws.on :message do |msg|
  puts ">> #{msg.data}"
end

ws.on :open do
  puts "-- websocket open (#{ws.url})"
end

ws.on :close do |e|
  puts "-- websocket close (#{e.inspect})"
  exit 1
end

ws.on :error do |e|
  puts "-- error (#{e.inspect})"
end

# loop do
#   ws.send STDIN.gets.strip
# end

begin
  redis.subscribe(:broadcast, :dat) do |on|
    on.subscribe do |channel, subscriptions|
      puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
    end

    on.message do |channel, message|
      puts "##{channel}: #{message}"
      ws.send message
      redis.unsubscribe if message == 'exit'
    end

    on.unsubscribe do |channel, subscriptions|
      puts "Unsubscribed from ##{channel} (#{subscriptions} subscriptions)"
    end
  end
rescue Redis::BaseConnectionError => e
  puts "#{e}, retrying in 1s"
  sleep 1
  retry
end
